from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from HomeAutoAI.common.Results import HttpResult
from users.entity.serializers import RegisterSerializer
from users.models import Users
from users.service.UserService import UserService


class RegisterView(APIView):
    """
    登录视图
    """

    def post(self, request, *args, **kwargs):
        serializer = RegisterSerializer(data=request.data)
        if serializer.is_valid():
            user = Users()
            if Users.objects.filter(username=serializer.validated_data['username']).exists():
                return HttpResult.error(data=serializer.errors, message='用户名已存在')
            else:
                # user: Users = serializer.save()  # 假设序列化器的 save 方法处理用户创建
                print(user.user_id)  # 打印用户 ID
                # 注册成功后，进行初始化账号操作，分配默认智慧家庭助手，分配默认Thread等等
                UserService.init_user(serializer)
                return HttpResult.success(data=serializer.data, message='注册成功')
        return HttpResult.error(data=serializer.errors, message='注册失败')

    def get(self, request, *args, **kwargs):
        return Response({'message': 'GET method not allowed.'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)

# TODO: 修改表结构，使用房间、住宅等与用户关联，实现权限的管理
